package com.roger.springcloudGreenwich.util;

import com.roger.springcloudGreenwich.config.EsClientPoolFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * ElasticSearch 连接池工具类
 */
@Component
public class ElasticSearchPoolUtil {
    private GenericObjectPool<RestHighLevelClient> clientPool;
    @Value("${pool.config.max-total}")
    private int maxTotal;
    // 要池化的对象的工厂类，这个是我们要实现的类
    @Autowired
    private EsClientPoolFactory esClientPoolFactory;

    /**
     * 获得对象
     *
     * @return
     * @throws Exception
     */
    @Bean(autowire = Autowire.BY_NAME,name = "restHighLevelClient")
    public RestHighLevelClient restHighLevelClient() throws Exception {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(maxTotal);
        clientPool = new GenericObjectPool<>(esClientPoolFactory,
                poolConfig);
        // 从池中取一个对象
        RestHighLevelClient client = clientPool.borrowObject();
        return client;
    }

    /**
     * 归还对象
     *
     * @param client
     */
    public void returnClient(RestHighLevelClient client) {
        // 使用完毕之后，归还对象
        clientPool.returnObject(client);
    }

    public static void main(String[] args) {
        String d = "";
    }

}
